package com.pocketsweet.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.GetCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.pocketsweet.MLApplication;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.chat.ui.activity.ChatActivity;
import com.pocketsweet.model.MLArticle;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.service.shareService;
import com.pocketsweet.service.shareService.shareCompleteListener;
import com.pocketsweet.ui.uilib.ActionItem;
import com.pocketsweet.ui.uilib.ActionSheetDialog;
import com.pocketsweet.ui.uilib.ActionSheetDialog.OnSheetItemClickListener;
import com.pocketsweet.ui.uilib.ActionSheetDialog.SheetItemColor;
import com.pocketsweet.ui.uilib.FlowLayout;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.ui.uilib.RandomColorTagView;
import com.pocketsweet.ui.uilib.Rotate3dAnimation;
import com.pocketsweet.ui.uilib.TagLayout;
import com.pocketsweet.ui.uilib.TagView;
import com.pocketsweet.ui.uilib.TitlePopup;
import com.pocketsweet.ui.uilib.TitlePopup.OnItemOnClickListener;
import com.pocketsweet.ui.uilib.wheelcity.wheelCity;
import com.pocketsweet.ui.uilib.wheelview.WheelMain;
import com.pocketsweet.ui.uilib.wheelview.WheelTimeContinued;
import com.pocketsweet.utils.ToolKits;
import com.pocketsweet.utils.selectPicUtils;

@ContentView(R.layout.activity_test)
public class Test extends BaseActivity {
	private Context ctx;
	@ViewInject(R.id.btnCallTest)
	private Button btnCallTest;
	@ViewInject(R.id.btnRecordTest)
	private Button btnRecordTest;
	@ViewInject(R.id.btnReportTest)
	private Button btnReportTest;
	@ViewInject(R.id.btnCityTest)
	private Button btnCityTest;
	@ViewInject(R.id.btnTimeTest)
	private Button btnTimeTest;
	@ViewInject(R.id.btnCutDown)
	private Button btnCutDown;
	@ViewInject(R.id.btnPhotoTest)
	private Button btnPhotoTest;
	@ViewInject(R.id.btnTitleTest)
	private Button btnTitleTest;
	@ViewInject(R.id.btnUserTest)
	private Button btnUserTest;
	@ViewInject(R.id.ivAvatar)
	private ImageView ivAvatar;
	private Button btnShareTest;
	@ViewInject(R.id.btnShareTest)
	WheelMain wheelMain;
	// 标签栏
	@ViewInject(R.id.btnAdd)
	private Button btnAdd;
	@ViewInject(R.id.edtLabel)
	private EditText edtLabel;
	@ViewInject(R.id.TagTest)
	private TagLayout TagTest;

	@ViewInject(R.id.RandomTagTest)
	private FlowLayout RandomTagTest;
	/** LayoutInflater */
	private LayoutInflater inflater;

	// 定义标题栏弹窗按钮
	private TitlePopup titlePopup;
	// 选择图片的bitmap
	private Bitmap myBitmap;
	private shareService myShareSevice;// 友盟分享service

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		ctx = this;
		UserService.displayAvatar(UserService.getCurrentUser().getAvatarUrl(),
				ivAvatar);
		// 实例化标题栏弹窗
		titlePopup = new TitlePopup(this, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		// 给标题栏弹窗添加子类
		titlePopup.addAction(new ActionItem(Test.this, "发起"));
		titlePopup.addAction(new ActionItem(this, "听筒"));
		titlePopup.addAction(new ActionItem(this, "登录"));
		titlePopup.addAction(new ActionItem(this, "扫一"));
		titlePopup.setItemOnClickListener(new OnItemOnClickListener() {

			@Override
			public void onItemClick(ActionItem item, int position) {
				switch (position) {
				case 0:
					ToolKits.toast(Test.this, "0");
					break;
				case 1:
					ToolKits.toast(Test.this, "1");
					break;
				case 2:
					ToolKits.toast(Test.this, "2");
					break;
				case 3:
					ToolKits.toast(Test.this, "3");
					break;
				default:
					break;
				}

			}
		});

		// init标签
		initTagTest();

		btnCallTest.setAnimation(AnimationUtils.loadAnimation(
				MLApplication.getContext(), R.anim.downup));
		// ivAvatar.setAnimation(AnimationUtils.loadAnimation(
		// MLApplication.getContext(), R.anim.rotate));
		// float centerX = ivAvatar.getWidth() / 2f;
		// float centerY = ivAvatar.getHeight() / 2f;
		// 构建3D旋转动画对象,旋转角度为0到90度 
		// Rotate3dAnimation rotation = new Rotate3dAnimation(0, 360, centerX,
		// centerY, 310.0f, true);
		// // 动画持续时间500毫秒 
		// rotation.setDuration(500);
		// // 动画完成后保持完成状态
		// rotation.setFillAfter(true);
		// rotation.setInterpolator(new AccelerateInterpolator());
		// 设置动画的监听器 
		Rotate3dAnimation rotation = new Rotate3dAnimation(0, 0, 0, 0, 0, true);

		rotation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationEnd(Animation arg0) {
				// 获取布局的中心点位置，作为旋转的中心点
				float centerX = ivAvatar.getWidth() / 2f;
				float centerY = ivAvatar.getHeight() / 2f;

				// 构建3D旋转动画对象,旋转角度为90到0度
				Rotate3dAnimation rotation = new Rotate3dAnimation(720, 0,
						centerX, centerY, 310.0f, false);
				// 动画持续时间500毫秒
				rotation.setDuration(500);
				// 动画完成后保持完成状态
				rotation.setFillAfter(true);
				rotation.setInterpolator(new AccelerateInterpolator());
				ivAvatar.startAnimation(rotation);
			}
		});
		ivAvatar.startAnimation(rotation);
	}

	private void initTagTest() {
		String[] stringTest = { "测试就发发发", "测试就发发发", "测试就发发发", "测试就发发发", "我就是我",
				"不一定", "我只是想是一个比较长的", "无聊", "无语",

				"小鲜肉" };
		// for (int i = 0; i < stringTest.length; i++) {
		// addLabel(stringTest[i]);
		// }
		LinkedList<View> list = new LinkedList<View>();
		for (int i = 0; i < stringTest.length; i++) {
			final TagView item = new TagView(Test.this);
			item.setName(stringTest[i]);
			item.getDelet().setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// 移除标签
					Animation anim = AnimationUtils.loadAnimation(Test.this,
							R.anim.unzoom_out);
					anim.setAnimationListener(new AnimationListener() {

						@Override
						public void onAnimationStart(Animation animation) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationRepeat(Animation animation) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationEnd(Animation animation) {
							TagTest.removeView(item.getTag().toString());

						}
					});
					item.startAnimation(anim);

				}
			});
			list.add(item);
		}

		TagTest.addALLView(list);

		btnAdd.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// 获取输入文字
				String label = edtLabel.getText().toString();
				// 非有效标签直接返回
				if (TextUtils.isEmpty(label.trim())) {
					return;
				} else {
					// 有效标签，添加
					addLabel(label);
				}
			}
		});

		for (int i = 0; i < stringTest.length; i++) {
			final RandomColorTagView itemView = new RandomColorTagView(
					Test.this);
			itemView.setText(stringTest[i]);
			itemView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
				}
			});
			RandomTagTest.addView(itemView);
		}
	}

	protected void addLabel(String label) {

		final TagView item = new TagView(Test.this);
		item.setName(label);
		item.getDelet().setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// 移除标签
				Animation anim = AnimationUtils.loadAnimation(Test.this,
						R.anim.unzoom_out);
				anim.setAnimationListener(new AnimationListener() {

					@Override
					public void onAnimationStart(Animation animation) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onAnimationRepeat(Animation animation) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onAnimationEnd(Animation animation) {
						TagTest.removeView(item.getTag().toString());

					}
				});
				item.startAnimation(anim);

			}
		});
		TagTest.addView(item);
	}

	@OnClick(R.id.btnCallTest)
	public void onCallTest(View view) {

	}

	@OnClick(R.id.btnRecordTest)
	public void onRecordTest(View view) {
		Intent recordintent = new Intent(Test.this, DialogAudio.class);
		Test.this.startActivity(recordintent);
	}

	@OnClick(R.id.btnCityTest)
	public void onCityTest(View view) {
		final wheelCity myWheelCity = new wheelCity(this);
		View cityview = myWheelCity.getView();
		final MyAlertDialog dialog1 = new MyAlertDialog(Test.this).builder()
				.setTitle(btnCityTest.getText().toString())

				.setView(cityview)
				.setNegativeButton("取消", new OnClickListener() {
					@Override
					public void onClick(View v) {

					}
				});
		dialog1.setPositiveButton("确定", new OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), myWheelCity.getText(),
						1).show();
			}
		});
		dialog1.show();
	}

	private static final String[] PLANETS = new String[] { "半小时（30时光）",
			"1小时（50时光）", "3小时（120时光）", "1天（200时光）", "7天（1200时光）", "30天（4500时光）" };
	private WheelTimeContinued wheelTimeContinued;
	private int selectedIndex = 2;// 当前选择时光,默认3小时
	private int costTime;// 花费的对应时光
	private int[] costTimes = { 30, 50, 120, 200, 1200, 4500 };

	@OnClick(R.id.btnTimeTest)
	public void onTimeTest(View view) {
		LayoutInflater inflater1 = LayoutInflater.from(Test.this);
		View timepickerview1 = inflater1.inflate(R.layout.wheeltime_continue,
				null);
		wheelTimeContinued = (WheelTimeContinued) timepickerview1
				.findViewById(R.id.wheeltime);
		wheelTimeContinued.setOffset(2);
		wheelTimeContinued.setItems(Arrays.asList(PLANETS));
		wheelTimeContinued.setSeletion(2);
		wheelTimeContinued
				.setOnWheelViewListener(new WheelTimeContinued.OnWheelViewListener() {
					@Override
					public void onSelected(int selected, String item) {
						// Log.e("===", "selectedIndex: " + selected +
						// ", mlUser: "
						// + mlUser);
						selectedIndex = selected - 2;
					}
				});
		final MyAlertDialog dialog = new MyAlertDialog(Test.this).builder()
				.setTitle("领走虚拟恋人").setView(timepickerview1)
				.setNegativeButton("取消", new OnClickListener() {
					@Override
					public void onClick(View v) {

					}
				});
		dialog.setPositiveButton("续时", new OnClickListener() {
			@Override
			public void onClick(View v) {
				costTime = costTimes[selectedIndex];
				// Log.e("===", "花费时光: " + costTime);

			}
		});
		dialog.show();
		// final wheelTime myWheelCity = new wheelTime(this);
		// View cityview = myWheelCity.getView();
		// final MyAlertDialog dialog1 = new MyAlertDialog(Test.this).builder()
		// .setTitle("领走虚拟恋人")
		//
		// .setView(cityview)
		// .setNegativeButton("取消", new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		//
		// }
		// });
		// dialog1.setPositiveButton("确定", new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// Toast.makeText(getApplicationContext(), myWheelCity.getText(),
		// 1).show();
		// }
		// });
		// dialog1.show();
	}

	@OnClick(R.id.btnCutDown)
	public void onTimeCutDown(View view) {

	}

	@OnClick(R.id.btnReportTest)
	public void onReportTest(View view) {
		new ActionSheetDialog(Test.this)
				.builder()
				.setTitle("举报类型")
				.setCancelable(true)
				.setCanceledOnTouchOutside(true)
				.addSheetItem("垃圾广告", SheetItemColor.Gray,
						new OnSheetItemClickListener() {
							@Override
							public void onClick(int which) {
								ToolKits.toast(Test.this, "垃圾广告");
							}
						})
				.addSheetItem("色情欺诈", SheetItemColor.Gray,
						new OnSheetItemClickListener() {
							@Override
							public void onClick(int which) {
								ToolKits.toast(Test.this, "色情欺诈");
							}
						})
				.addSheetItem("骚扰谩骂", SheetItemColor.Gray,
						new OnSheetItemClickListener() {
							@Override
							public void onClick(int which) {
								ToolKits.toast(Test.this, "骚扰谩骂");
							}
						})
				.addSheetItem("政治敏感", SheetItemColor.Gray,
						new OnSheetItemClickListener() {
							@Override
							public void onClick(int which) {
								ToolKits.toast(Test.this, "政治敏感");
							}
						}).show();
	}

	@OnClick(R.id.btnPhotoTest)
	public void onPhoneTest(View view) {
		new ActionSheetDialog(this)
				.builder()
				.setCancelable(true)
				.setCanceledOnTouchOutside(true)
				.addSheetItem("从相册选择", SheetItemColor.Gray,
						new OnSheetItemClickListener() {
							@Override
							public void onClick(int which) {
								selectPicUtils.openLocalImage(Test.this);
							}
						})
				.addSheetItem("拍照", SheetItemColor.Gray,
						new OnSheetItemClickListener() {
							@Override
							public void onClick(int which) {
								selectPicUtils.openCameraImage(Test.this);
							}
						}).show();
	}

	@OnClick(R.id.btnTitleTest)
	public void onTitleTest(View view) {
		titlePopup.show(view);
	}

	@OnClick(R.id.btnUserTest)
	public void onUserTest(View view) {
		Intent chatIntent = new Intent(Test.this, ChatActivity.class);
		chatIntent.putExtra("userId", "MLCUSTOM");
		chatIntent.putExtra("avatar", "");
		chatIntent.putExtra("nickName", "在线客服");
		startActivity(chatIntent);
	}

	@SuppressWarnings("unchecked")
	@OnClick(R.id.ivAvatar)
	public void onAvatarTest(View view) {
		Intent imgintent = new Intent(Test.this, ImageViewFlipper.class);
		@SuppressWarnings("rawtypes")
		ArrayList<String> mBigImagePath = new ArrayList<String>();
		mBigImagePath.add(UserService.getCurrentUser().getAvatarUrl());
		imgintent.putStringArrayListExtra("ImageList", mBigImagePath);
		imgintent.putExtra("index", 0);
		Test.this.startActivity(imgintent);
	}

	@OnClick(R.id.btnShareTest)
	public void onShareTest(View view) {
		// 社会化分享
		AVQuery<MLArticle> query = new AVQuery<MLArticle>("MLArticle");
		query.include("title_img");
		query.getInBackground("5518b495e4b05957d5ae4690",
				new GetCallback<MLArticle>() {

					@Override
					public void done(MLArticle article, AVException arg1) {
						if (arg1 == null) {
							myShareSevice = new shareService(ctx, article);
							myShareSevice
									.setCompleteListener(new shareCompleteListener() {

										@Override
										public void onComplate() {
											// TODO Auto-generated method stub

										}
									});
							myShareSevice.startShare();
						} else {
							ToolKits.toast(ctx, "分享错误");
						}
					}
				});

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_CANCELED) {
			return;
		}
		switch (requestCode) {
		case selectPicUtils.GET_IMAGE_BY_CAMERA:
			if (selectPicUtils.imageUriFromCamera != null) {
				selectPicUtils.cropImage(this,
						selectPicUtils.imageUriFromCamera, 300, 300);
				break;
			}

			break;
		case selectPicUtils.GET_IMAGE_FROM_PHONE:
			if (data != null && data.getData() != null) {
				selectPicUtils.cropImage(this, data.getData(), 300, 300);
			}
			break;
		case selectPicUtils.CROP_IMAGE:
			if (selectPicUtils.cropImageUri != null) {
				File avatarCrop = selectPicUtils.createFileFromUri(
						selectPicUtils.cropImageUri, Test.this);
				UserService.displayAvatar(
						"file://" + avatarCrop.getAbsolutePath(), ivAvatar);
				try {
					AVFile avatar = AVFile.withAbsoluteLocalPath(
							avatarCrop.getName(), avatarCrop.getAbsolutePath());
					// 获取当前的用户
					final MLUser user = UserService.getCurrentUser();
					user.setAvatar(avatar);
					user.saveInBackground();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			break;
		default:
			break;
		}
	}
}
